package lagou.homework.lagou_homework_rocketmq.consumer;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import lagou.homework.lagou_homework_rocketmq.entity.*;
import lagou.homework.lagou_homework_rocketmq.repository.GoodsRepository;
import lagou.homework.lagou_homework_rocketmq.repository.OrderRepository;
import lagou.homework.lagou_homework_rocketmq.repository.SeckillRepository;
import lagou.homework.lagou_homework_rocketmq.repository.SeckillVoRepository;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Optional;

@Slf4j
@Component
@RocketMQMessageListener(topic = "order_create", consumerGroup = "order_create_consumer")
public class CreateOrderConsumer implements RocketMQListener<String> {
    @Autowired
    private OrderRepository orderRepository;
    @Autowired
    private SeckillVoRepository seckillVoRepository;
    @Autowired
    private GoodsRepository goodsRepository;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    /**
     * 异步创建订单
     * @param msg
     */
    @Override
    public void onMessage(String msg) {
        log.info("create_order队列监听到创建订单消息:\n{}", msg);
        CreateOrderMessage createOrderMessage = JSON.parseObject(msg,CreateOrderMessage.class);
        /**
         * 查询秒杀
         */
        SeckillVo seckillVo = seckillVoRepository.findById(createOrderMessage.getSeckillId()).get();

        /**
         * 生成订单，保存到数据库
         */
        Order order = new Order();
        order.setOrderNo(createOrderMessage.getOrderNo());
        order.setUserId(createOrderMessage.getUserId());
        order.setGoodsId(seckillVo.getGoods().getGoodsId());
        order.setSeckillId(createOrderMessage.getSeckillId());
        order.setGoodsName(seckillVo.getGoods().getName());
        order.setNum(1);
        order.setStatus(0);
        order.setCreateTime(new Date());
        order.setPayTime(new Date());
        order.setExpireTime(DateUtils.addMinutes(new Date(),2));
        order.setRealPrice(seckillVo.getCurrentPrice());
        orderRepository.save(order);
        log.info("创建订单：{}",order.getOrderNo());
        /**
         * 减库存
         */
        goodsRepository.decreaseStock(seckillVo.getGoods().getGoodsId(),1);

        /**
         * 创建延时队列，监听支付
         */
        TimeoutOrderMessage timeoutOrderMessage = new TimeoutOrderMessage(order,seckillVo.getSeckillId());
        String message = JSON.toJSONString(timeoutOrderMessage);
        // 向延迟队列发送消息
        rocketMQTemplate.asyncSend("order_timeout", // 到哪个主题
                MessageBuilder.withPayload(message).build(), // 消息
                new SendCallback() { // 回调
                    @Override
                    public void onSuccess(SendResult sendResult) {
                       log.info("延迟消息发送成功,msgId:{}",sendResult.getMsgId());
                    }

                    @Override
                    public void onException(Throwable throwable) {
                        throwable.printStackTrace();
                        System.err.println(throwable.getLocalizedMessage());
                    }
                },
                3000, // 发送超时时间
                3 // 延迟30秒
        );
    }
}
